<template>
  <div v-if="currentUser && show" class="pay" @click.stop="hide">
    <div class="item" @click.stop>
      <label><input type="password" v-model="password" placeholder="请输入用户密码" autofocus></label>
      <div class="pay-btn" @click="pay">支付</div>
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  export default {
    name: 'Pay',
    props: ['show'],
    computed: {
      ...mapGetters([
        'cartList'
      ]),
      // 合计
      totalPrice() {
        return this.cartList.filter(item => {
          return item.checked
        }).reduce((preValue, item) =>{
          return preValue + item.price * item.count
        },0).toFixed(2)
      },
      // 选中的商品列表
      checkGoods() {
        return this.cartList.filter(item => item.checked)
      },
      currentUser() {
        return sessionStorage.getItem("username")
      }
    },
    data() {
      return {
        password: ''
      }
    },
    methods: {
      hide() {
        this.$emit('hide')
        this.password =''
      },
      pay() {
        if(this.password === sessionStorage.getItem('password')) {
          // 判断余额是否足够
          var money = this.$store.state.my[0]
          if(money < this.totalPrice) {
            this.$toast.show('余额不足', 2000)
          } else {
            this.$store.commit('pay', {
              pay: this.totalPrice,
              goods: this.checkGoods
            })
            this.$toast.show('购买成功', 2000)
          }
        } else {
          this.$toast.show('密码错误', 2000)
        }
        this.hide()
        this.password =''
      }
    }
  }
</script>

<style scoped>
  .pay {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 11;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.4);
  }
  .item {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    width: 60vw;
    background-color: #fff;
    text-align: center;
    padding: 1rem;
  }
  input{
    width: 100%;
    margin-top: 0.5rem;
  }
  .pay-btn {
    background-color: blue;
    color: #fff;
    padding: 0.3rem 0;
    margin-top: 0.5rem;
  }
</style>